<template>
  <my-container>
    <vxe-grid
      ref="xGrid"
      border
      resizable
      :radio-config="{highlight:true}"
      :export-config="{
        modes:['current', 'selected', 'all']}"
      stripe
      auto-resize
      show-overflow
      size="small"
      height="auto"
      :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
      :pager-config="tablePage"
      :toolbar="tableToolbar"
      :proxy-config="proxyConfig"
      :loading="listLoading"
      :columns="tableColumn"
      @page-change="pageChange"
    >
      <template v-slot:toolbar_buttons>
        <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="filter.name"
              placeholder="计量编号"
              clearable
              @keyup.enter.native="getMachineCheckList"
            >
              <template #prefix>
                <i class="el-input__icon el-icon-search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="checkPermission(['api:quality:machinecheck:getownerpage'])">
            <el-button icon="el-icon-search" type="primary" @click="getMachineCheckList">查询</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template v-slot:status_default="{ row, rowIndex }">
        <!-- row.status==-1?"正常":row.status==0?"校验中":row.status==1?"待确认":row.status==2?"校验失败":"" -->
        <el-tag :type="row.status =='正常'?'success':row.status =='校验中'?'':row.status =='待确认'?'warning':row.status =='校验失败'?'danger':'info' ">{{ row.status }}</el-tag>
      </template>
      <!-- :pager-config="{pageSize: 10}" -->
      <template v-if="checkPermission(['api:quality:checkresport:add'])" v-slot:operate="{$index, row }">
        <vxe-button v-if="checkPermission(['api:quality:checkresport:add'])" icon="fa fa-edit" title="提交校验报告" circle @click="onEdit($index,row)" />
      </template>
    </vxe-grid>

    <vxe-modal
      v-if="checkPermission(['api:quality:checkresport:add'])"
      v-model="modalAddShow"
      :loading="submitLoading"
      title="添加校准信息"
      width="500"
      height="340"
      destroy-on-close
      resize
      @close="closeAddForm"
    >
      <vxe-form ref="addForm" :data="addForm" :rules="addFormRules" title-align="right" title-width="120" @submit="onAddSubmit">
        <vxe-form-item title="校准时间" field="calTime" span="24" :item-render="{name: '$input', props: { type: 'date', placeholder: '请选择日期' }}" />
        <!-- <vxe-form-item title="校验结果描述" field="result" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入校验结果描述'}}" /> -->
        <vxe-form-item title="校验结果描述" field="result" span="24">
          <vxe-textarea v-model="addForm.result" placeholder="请输入校验结果描述" size="mini" />
        </vxe-form-item>
        <vxe-form-item title="检验文档" field="filePath" span="24" :title-prefix="{ message: '上传检验报告！！！' }">
          <template v-slot>
            <el-upload
              v-model="addForm.filePath"
              v-loading="avatarLoading"
              class="avatar-uploader"
              action="/api/quality/checkresport/fileupload"
              :limit="1"
              :headers="token"
              :before-upload="()=>{avatarLoading = true}"
              :on-success="onAvatarSuccess"
              :on-error="onAvatarError"
              style="display: inline-block;"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">限上传一个，只能上传xls/xlsx/docx/doc文件,不能超过10M</div>

            </el-upload>
          </template>
        </vxe-form-item>
        <vxe-form-item align="right" span="24">
          <vxe-button @click="addclose()">取消</vxe-button>
          <vxe-button type="submit" status="primary">提交</vxe-button>
        </vxe-form-item>
      </vxe-form>
      <!-- <template v-slot:footer>
        <vxe-button @click="addclose()">取消</vxe-button>
        <my-confirm-button type="submit" status="primary" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
      </template> -->
    </vxe-modal>

    <vxe-modal v-if="checkPermission(['api:quality:checkresport:update'])" v-model="editFormVisible" :loading="submitLoading" title="编辑设备校验" width="500" height="340" destroy-on-close resize>
      <vxe-form :data="editForm" :rules="editFormRules" title-align="right" title-width="120" @submit="onEditSubmit">
        <vxe-form-item title="校准时间" field="calTime" span="24" :item-render="{name: '$input', props: { type: 'date', placeholder: '请选择日期' }}" />
        <!-- <vxe-form-item title="校验结果描述" field="result" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入校验结果描述'}}" /> -->
        <vxe-form-item title="校验结果描述" field="result" span="24">
          <vxe-textarea v-model="editForm.result" placeholder="请输入校验结果描述" size="mini" />
        </vxe-form-item>

        <vxe-form-item title="检验文档" field="filePath" span="24" :title-prefix="{ message: '上传检验报告！！！' }">
          <template v-slot>
            <el-upload
              v-loading="calLoading"
              class="avatar-uploader"
              action="/api/quality/checkresport/fileupload"
              :limit="1"
              :headers="token"
              :before-upload="()=>{calLoading = true}"
              :on-success="oncalSuccess"
              :on-error="oncalError"
              style="display: inline-block;"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">限上传一个，只能上传xls/xlsx/docx/doc文件,不能超过10M</div>
            </el-upload>
          </template>
        </vxe-form-item>
        <vxe-form-item align="right" span="24">
          <vxe-button @click="addclose()">取消</vxe-button>
          <vxe-button type="submit" status="primary">提交</vxe-button>
        </vxe-form-item>
      </vxe-form>
      <!-- <template v-slot:footer>
        <vxe-button @click="editclose()">取消</vxe-button>
        <vxe-button type="submit" status="primary" @click="onEditSubmit()">提交</vxe-button>
      </template> -->
    </vxe-modal>

  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
// import { removeXbcWarehouse, batchRemoveXbcWarehouse } from '@/api/warehouse/xbcwarehouse'
import { getxbcLocationList } from '@/api/warehouse/xbclocation'
import { getWlffdwList } from '@/api/admin/dictionary'
import { getOwnerMachineCheckListPage, editMachineCheck } from '@/api/quality/machinecheck'
import { addCheckResport, getCheckResport, editCheckResport } from '@/api/quality/checkreport'
import { getUserList } from '@/api/admin/user'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Stocklist',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        name: ''
      },
      typeList: [
        { label: '内部校验', value: 0 },
        { label: '外部校验', value: 1 }
      ],
      dw: [
        { label: '年', value: 1 },
        { label: '月', value: 2 }
      ],
      bmList: [],
      gysList: [],
      usrList: [],
      conf: {
        isTerm: false, // 是否有效期
        isRegLlBatch: false, // 是否记录来料批次
        isSingle: false, // 是否单个入库
        isProduceNumb: false, // 是否生成编号
        prefix: '', // 编号前缀
        canReturn: false, // 是否要归还
        isThawWare: false, // 是否有解冻仓库
        isRegEquip: false, // 出库是否记录设备号
        isRegProduBatch: false, // 是否记录产品批号
        isRegMaterArriDate: false, // 是否记录来料日期
        isRegPcbLot: false, // 是否等级pcblot号
        showCustomCode: false // 是否显示客户代码
      },
      addFormRules: {
        calTime: [{ required: true, message: '请输入校验时间', trigger: 'blur' }],
        result: [{ required: true, message: '请输入校验描述', trigger: 'blur' }],
        filePath: [{ required: true, message: '请添加附件', trigger: 'blur' }]
      },
      editFormRules: {
        calTime: [{ required: true, message: '请输入校验时间', trigger: 'blur' }],
        result: [{ required: true, message: '请输入校验描述', trigger: 'blur' }],
        filePath: [{ required: true, message: '请添加附件', trigger: 'blur' }]
      },
      tableToolbar: {
        custom: true,
        export: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      mfilter: {
        wlId: null, // 物料id
        kwId: null// 库位id wlId: this.filter.wlId, kwId: this.filter.kwId
      },
      mtableToolbar: {
        export: true,
        custom: true
      },
      cvisible: false,
      submitLoading: false,
      modalShow: false,
      roles: [],
      statusList: [
        { name: '激活', value: true },
        { name: '禁用', value: false }
      ],
      xbcTypeList: [], // 物料分类下拉
      xbcLocationList: [], // 库位下拉
      wlffdwList: [], // 物料最小发放单位
      wlffslList: [], // 物料最小发放数量
      khdmList: [], // 客户代码
      ckdwList: [], // 库存单位列表
      mproxyConfig: {
        // seq: true, // 启用动态序号代理
        // sort: true, // 启用排序代理
        // filter: true, // 启用筛选代理
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）
          query: async({ page, sort, filters, form }) => {
            // 处理排序条件
            const para = {
              currentPage: page.currentPage,
              pageSize: page.pageSize,
              filter: this.mfilter
            }
            this.mloading = true
            const res = await getStockDetailListPage(para)
            this.mloading = false

            if (!res?.success) {
              return
            }
            return res.data
          },
          // 被某些特殊功能所触发，例如：导出数据 mode=all 时，会触发该方法并对返回的数据进行导出
          queryAll: () => getAllDetailPage({ wlId: this.mfilter.wlId, kwId: this.mfilter.kwId
          })
        }
      },
      proxyConfig: {
        seq: true, // 启用动态序号代理
        // sort: true, // 启用排序代理
        // filter: true, // 启用筛选代理
        props: {
          result: 'result',
          total: 'page.total'
        },
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）, sort, filters, form
          query: async({ page }) => {
            // 处理排序条件
            const para = {
              currentPage: this.tablePage.currentPage, // page.currentPage
              pageSize: this.tablePage.pageSize, // page.pageSize
              filter: this.filter
            }
            this.listLoading = true
            const res = await getOwnerMachineCheckListPage(para)
            this.listLoading = false
            if (!res?.success) {
              return
            }
            this.tablePage.total = res.data.page.total
            // const data = res.data.list
            // data.forEach(d => {
            //   d._loading = false
            // })
            // console.log('ccc', res.data)
            if (!res?.success) {
              return
            }
            return res.data
          },
          // 被某些特殊功能所触发，例如：导出数据 mode=all 时，会触发该方法并对返回的数据进行导出
          queryAll: () => getAllPage({ name: this.filter.name, id: this.filter.xbcTypeId
            // currentPage: 0,
            // pageSize: 0,
            // filter: this.filter
          })
        }
      },
      tableColumn: [],
      mtableColumn: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      pager: {},
      listLoading: false,
      mloading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      addLoading: false,
      // 编辑界面数据
      editForm: {
        id: null,
        machineCheckId: null,
        calTime: null, // 校验时间
        result: '', // 描述
        filePath: '' // 检验报告
      },
      editFormRef: null,
      modalAddShow: false,
      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      // 新增界面数据
      addForm: {
        machineCheckId: null,
        calTime: null, // 校验时间
        result: '', // 描述
        filePath: null // 检验报告
      },
      avatarLoading: false,
      calLoading: false,
      addFormRef: null,
      deleteLoading: false
    }
  },
  computed: {
    token() {
      return { 'Authorization': 'Bearer ' + this.$store.getters.token }
    }
  },
  mounted() {
    this.tableColumn = [
      { type: 'radio', width: 50 },
      { type: 'seq', width: 60 },
      { field: 'calTypeName', title: '校验类型' },
      { field: 'controlNo', title: '计量编号', width: 100 },
      { field: 'equipmentName', title: '设备名称' },
      { field: 'equipmentNo', title: '设备号' },
      { field: 'serialNo', title: '序列号' },
      { field: 'model', title: '型号' },
      { field: 'accuracy', title: '精度', visible: false },
      { field: 'referenceDoc', title: '参考文档', visible: false },
      { field: 'depermentName', title: '所属部门' },
      { field: 'ownerName', title: '责任人' },
      { field: 'calCycle', title: '计量周期' },
      { field: 'planCalTime', title: '计划校准时间', formatter: this.formatDate, width: 100 },
      { field: 'calibrationEquipment', title: '校准设备' },
      { field: 'controlItem', title: '未知字段', visible: false },
      { field: 'planSupplierName', title: '送检供应商' },
      { field: 'calibrationReq', title: '校准要求' },
      { field: 'enabled', title: '是否可用', cellRender: { name: 'ElSwitch', props: { disabled: true }}},
      { field: 'remark', title: '备注', visible: false },
      { field: 'status', title: '状态', width: 90, slots: {
        // 对应自定义插槽的名称
        default: 'status_default'
      }}
    ]
    // console.log('ff')
    if (this.checkPermission(['api:quality:checkresport:add'])) {
      this.tableColumn.push({ title: '操作', width: 100, slots: { default: 'operate' }})
    }
    // this.$refs.xGrid.commitProxy('reload')
    // this.getXbcmaterrials()
  },
  methods: {
    // 上传成功
    onAvatarSuccess(res) {
      this.avatarLoading = false
      if (!res?.code === 1) {
        return
      }
      // console.log('f', res.data)
      this.addForm.filePath = res.data
    },
    addclose() {
      this.modalAddShow = false
      this.closeAddForm()
    },
    // 上传失败
    onAvatarError(err, file) {
      this.avatarLoading = false
      const res = err.message ? JSON.parse(err.message) : {}
      if (!(res?.code === 1)) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    },
    // 上传成功
    oncalSuccess(res) {
      this.calLoading = false
      if (!res?.code === 1) {
        return
      }
      // console.log('f', res.data)
      this.editForm.filePath = res.data
    },
    // 上传失败
    oncalError(err, file) {
      this.calLoading = false
      const res = err.message ? JSON.parse(err.message) : {}
      if (!(res?.code === 1)) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    async pageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
    },
    // 汇总列表
    async  getMachineCheckList() {
      if (this.$refs.xGrid) {
        this.$nextTick(() => {
          this.$refs.xGrid.commitProxy('reload')
        })
      }

      // this.$refs.xGrid.commitProxy('reload')
    },
    // 编辑
    async onEditSubmit() {
      this.submitLoading = true
      const para = _.cloneDeep(this.editForm)
      const res = await editCheckResport(para)
      this.submitLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      // this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.getMachineCheckList()
    },
    // 新增验证
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 新增
    async onAddSubmit() {
      this.addLoading = true
      this.submitLoading = true
      const para = _.cloneDeep(this.addForm)
      const res = await addCheckResport(para)
      this.submitLoading = false
      this.addLoading = false
      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.modalAddShow = !this.modalAddShow
      this.getMachineCheckList()
    },
    async changeValue() {
      this.tableColumn = [
        { type: 'radio', width: 50 },
        { type: 'seq', width: 60 },
        { field: 'calTypeName', title: '校验类型' },
        { field: 'controlNo', title: '计量编号', width: 100 },
        { field: 'equipmentName', title: '设备名称' },
        { field: 'equipmentNo', title: '设备号' },
        { field: 'serialNo', title: '序列号' },
        { field: 'model', title: '型号' },
        { field: 'accuracy', title: '精度', visible: false },
        { field: 'referenceDoc', title: '参考文档', visible: false },
        { field: 'depermentName', title: '所属部门' },
        { field: 'ownerName', title: '责任人' },
        { field: 'calCycle', title: '计量周期' },
        { field: 'planCalTime', title: '计划校准时间', formatter: this.formatDate, width: 100 },
        { field: 'calibrationEquipment', title: '校准设备' },
        { field: 'controlItem', title: '未知字段' },
        { field: 'planSupplierName', title: '送检供应商' },
        { field: 'calibrationReq', title: '校准要求' },
        { field: 'enabled', title: '是否可用', cellRender: { name: 'ElSwitch', props: { disabled: true }}},
        { field: 'remark', title: '备注', visible: false },
        { field: 'status', title: '状态', slots: {
        // 对应自定义插槽的名称
          default: 'status_default'
        }}
      ]
      // console.log('ff')
      if (this.checkPermission(['api:quality:checkresport:add'])) {
        this.tableColumn.push({ title: '操作', width: 100, slots: { default: 'operate' }})
      }
    },
    // 显示新增界面
    async onAdd() {
      const loading = this.$loading()
      // this.modalShow = !this.modalShow
      if (this.bmList.length === 0) {
        await this.getWlffdwList('ZL_SYBM')
      }
      if (this.gysList.length === 0) {
        await this.getWlffdwList('PL_SUPER')
      }
      if (this.usrList.length === 0) {
        await this.getUserList()
      }
      loading.close()
      this.modalAddShow = !this.modalAddShow
    },
    async getUserList() {
      const res = await getUserList()
      if (res && res.success) {
        this.usrList = res.data
      }
    },
    async getWlffdwList(id) {
      const res = await getWlffdwList({ dicCode: id })
      if (res && res.success) {
        if (id === 'ZL_SYBM') {
          this.bmList = res.data
        }
        if (id === 'PL_SUPER') {
          this.gysList = res.data
        }
      }
    },
    // 显示编辑界面
    async onEdit(index, row) {
      if (row.status === '正常' || row.status === '校验中') {
        // const loading = this.$loading()
        this.addForm = {
          machineCheckId: row.id,
          calTime: null, // 校验时间
          result: '', // 描述
          filePath: '' // 检验报告
        }
        // this.addForm.machineCheckId = row.id
        this.modalAddShow = !this.modalAddShow
        // loading.close()
      } else if (row.status === '待确认') {
        this.editFormVisible = true
        this.submitLoading = true
        // const loading = this.$loading()
        const res = await getCheckResport({ id: row.id })
        // loading.close()
        if (res && res.success) {
          const data = res.data
          this.editForm = data
          this.editGetxbcLocationList(this.editForm.xbcTypeId)
          this.submitLoading = false
        }
      } else {
        this.$message({
          message: '异常状态业务待确认',
          type: 'warning'
        })
      }
    },
    closeEditForm() {
    },
    closeAddForm() {
      this.addForm = {
        machineCheckId: null,
        calTime: null, // 校验时间
        result: '', // 描述
        filePath: '' // 检验报告
      }
    },
    // 编辑验证
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    editclose() {
      this.editFormVisible = false
    },
    async getxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
        this.addForm.xbcLocationId = null
        this.editForm.xbcLocationId = null
      }
    },
    async editGetxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
      }
    },
    selsChange: function(sels) {
      this.sels = sels
    }
  }
}
</script>
